package edu.iss.javaproject.controller;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import edu.iss.javaproject.exception.LeaveNotFoundException;
import edu.iss.javaproject.exception.UserNotFoundException;
import edu.iss.javaproject.model.LeaveRecord;
import edu.iss.javaproject.model.PublicHolidays;
import edu.iss.javaproject.model.Users;
import edu.iss.javaproject.service.LAPService;
import edu.iss.javaproject.util.ConvertDate;

@Controller
@RequestMapping(value = "/adminHome")
@SessionAttributes(value="sessionuser")
public class AdminController {
	
	private static final Logger logger = LoggerFactory.getLogger(AdminController.class);
	@Autowired
	private LAPService lapservice;
	
	@RequestMapping(value = "", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate );
		
		return "adminHome";
	}

//	@RequestMapping(value = "/EmpList", method = RequestMethod.GET)
//	public ModelAndView UserListPage() {
//		ModelAndView mav = new ModelAndView("EmpList");
//		HashMap<Integer,Users> userMap = new HashMap<Integer,Users>();
//		List<Users> userList = lapservice.findAllUsers();
//		int noOfPages=1;
//		for(int i=0;i<userList.size();i++)
//		{
//			noOfPages= (int) Math.ceil(i/10);
//			userMap.put(noOfPages, userList.get(i));
//		}
//		mav.addObject("noOfPages", userMap);
//		mav.addObject("UsersList", userList);
//		return mav;
//	}
	@RequestMapping(value = "/EmpList", method = RequestMethod.GET)
	public ModelAndView UserListByPage(@RequestParam(value="pageNo", required=false,defaultValue="1") int no) {
		ModelAndView mav = new ModelAndView("EmpList");
		List<Users> userList = lapservice.findAllUsers();
		List<Users> currentPage = new ArrayList<Users>();
		
		HashMap<Integer,Users> userMap = new HashMap<Integer,Users>();
		int noOfPages=1;
		for(int i=0;i<userList.size();i++)
		{
			noOfPages= (int) Math.ceil(i/10);
			userMap.put(noOfPages, userList.get(i));
		}
		mav.addObject("noOfPages", userMap);
		mav.addObject("currentNO", no);
		no=no*10;

		logger.info("NOOOOOO "+ no);
		int start=0;
		if(no<userList.size())
		{
			start=no;
			no=no+10;
			
		}
		if(no>=userList.size())
		{
			logger.info("INNNNNN "+ no);
			start=no-10;
			no=userList.size();	
		}
		for(int i=start;i<no;i++)
		{
			currentPage.add(userList.get(i));
			
		}
		mav.addObject("UsersList", currentPage);
		return mav;
	}
	
	
	
	
	

	@RequestMapping(value = "/EmpList/delete/{users.id}", method = RequestMethod.POST)
	public ModelAndView deleteStudent(@PathVariable("users.id") Integer id,
			final RedirectAttributes redirectAttributes)
			throws UserNotFoundException {

		ModelAndView mav = new ModelAndView("redirect:/adminHome");

		lapservice.deleteUser(lapservice.findByID(id));
		return mav;
	}


	

	@RequestMapping(value = "/EmpList/create", method = RequestMethod.GET, params = "create")
	public ModelAndView newEmployeePage() {
		ModelAndView mav = new ModelAndView("NewEmp", "user", new Users());
		return mav;
	}

	@RequestMapping(value = "/EmpList/create", method = RequestMethod.POST, params = "create")
	public ModelAndView createNewEmployee(@ModelAttribute @Valid Users user,
			BindingResult result, final RedirectAttributes redirectAttributes) {

		if (result.hasErrors())
			return new ModelAndView("NewEmp");

		ModelAndView mav = new ModelAndView();
		String message = "New Employee " + user.getName()
				+ " was successfully created.";
		mav.setViewName("redirect:/adminHome/EmpList/create");
		lapservice.save(user);
		mav.setViewName("redirect:/adminHome");

		redirectAttributes.addFlashAttribute("message", message);
		return mav;
	}

	@RequestMapping(value = "/EmpList/edit/{users.id}", method = RequestMethod.GET)
	public ModelAndView requesteditStudent(@PathVariable("users.id") Integer id,
			final RedirectAttributes redirectAttributes)
			throws UserNotFoundException {

		ModelAndView mav = new ModelAndView("Edit");
		
		System.out.println(id);
		
		Users u = lapservice.findByID(id);
		 
		mav.addObject("user", u);
		return mav;
	}
	@RequestMapping(value = "/EmpList/edit/{users.id}", method = RequestMethod.POST)
	public ModelAndView editStudent(@PathVariable("users.id") Integer id,@ModelAttribute("sessionuser") Users user,
			final RedirectAttributes redirectAttributes)
			throws UserNotFoundException {

		ModelAndView mav = new ModelAndView("redirect:/adminHome/EmpList");
		
		System.out.println(id);
		System.out.println(user.toString());
		lapservice.update(user);
		
		return mav;
	}
	@RequestMapping(value = "/Holidays", method = RequestMethod.GET)
	public ModelAndView Holidays ()
	{
		ModelAndView Hol = new ModelAndView("Holidays");
		List<PublicHolidays> Holidaylist=(List<PublicHolidays>)lapservice.findAllPublicHoliday();
		Hol.addObject("Holidaylist",Holidaylist);
		return Hol;
		
	}
	@RequestMapping(value="/Add",method=RequestMethod.GET)
	public String setupForm(Map<String, Object> map){
		PublicHolidays Holiday = new PublicHolidays();
		map.put("Holiday", Holiday);
		map.put("HolidayList", lapservice.findAllPublicHoliday());
		return "AddHoliday";
	}
	@RequestMapping(value="/AddHoliday", method=RequestMethod.POST)
	public String doActions(@ModelAttribute PublicHolidays Holiday, BindingResult result, @RequestParam String action, Map<String, Object> map)
	{
		
		lapservice.save(Holiday);
		
		map.put("Holidaylist", lapservice.findAllPublicHoliday());
		return "redirect:/adminHome/Holidays";
}
	@RequestMapping(value = "/movementRegister", method = RequestMethod.GET)
	public ModelAndView movementRegister(@RequestParam(value="month", required=false, defaultValue ="1") String date,@ModelAttribute("sessionuser") Users user) throws UserNotFoundException, LeaveNotFoundException {
		logger.info("Welcome home! The client locale is {}.",user.toString());
		HashMap<Integer,Users> map = new HashMap<Integer,Users>();
		ModelAndView mv = new ModelAndView("movementRegister");
		List<LeaveRecord> list = lapservice.findAllLeaveRecords();
		List<LeaveRecord> listRecord = new ArrayList<LeaveRecord>();
		ConvertDate cd = new ConvertDate();
		Date start;
		Date end;
		int realDate = Integer.valueOf(date)-1;
		logger.info("Month is "+ realDate);
		for(int i=0;i<list.size();i++)
		{
			start= list.get(i).getLeaveStart();
			end = list.get(i).getLeaveEnd();
			logger.info("Month is "+cd.GetMoth(start));
			if(cd.GetMoth(start)==realDate|| cd.GetMoth(end)==realDate)
			{
				
				listRecord.add(list.get(i));
				map.put(i, lapservice.findByID(list.get(i).getId()));
			}
		}
		mv.addObject("staffRecord", map );
		mv.addObject("leaveRecord", listRecord);
		
		return mv;
	}
	

}
